package com.harvest.scientific.ladder.page

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActInfo2Binding
import com.harvest.scientific.ladder.ext.asLifecycleOwner
import com.harvest.scientific.ladder.ext.visible
import com.harvest.scientific.ladder.res.RememberBlankAntRes
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.ToastUtil
import com.harvest.scientific.ladder.wheel.wheelpicker.RelationShipPicker
import com.harvest.scientific.ladder.wheel.wheelpicker.SecondRelationShipPicker


class Info2Activity: BaActivity(),View.OnClickListener {

    private lateinit var binding: ActInfo2Binding

    private lateinit var relationShipPicker: RelationShipPicker
    private var relationShip: RememberBlankAntRes?= null

    private lateinit var secondRelationShipPicker: SecondRelationShipPicker
    private var secondRelationShip: RememberBlankAntRes?= null

    private var isGetContactSuc = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActInfo2Binding.inflate(layoutInflater)
        setContentView(binding.root)
        initEvent()
        initTextChangedListener()
        initObserver()
        initData()

    }

    private fun initData() {
        relationShipPicker = RelationShipPicker(this)
        secondRelationShipPicker = SecondRelationShipPicker(this)
        appModel.rememberBlankAnt("relationship")
        appModel.rememberBlankAnt("secRelationship")
        appModel.fleeSocialistExpedition(3)
    }

    private fun initObserver() {
//        FlowBus.with<Unit>(FlowBusConstant.CLOSE_INFO).register(this) {
//            finish()
//        }

        appModel.showLoading.observe(asLifecycleOwner) {
            if (it) showLoading() else dismissLoading()
        }

        appModel.relationshipSuc.observe(asLifecycleOwner) {
            relationShipPicker.setJSON(it)
        }
        appModel.secRelationshipSuc.observe(asLifecycleOwner) {
            relationShipPicker.setJSON(it)
        }
        appModel.searchInfo2.observe(asLifecycleOwner) {result ->
            result?.let {
                if (!it.compressedAnybodyPyramid.isNullOrEmpty() && !it.thirstyCookiePrivateSurface.isNullOrEmpty()) {
                    relationShip = RememberBlankAntRes()
                    relationShip?.furnishedLetterConnection = it.compressedAnybodyPyramid
                    relationShip?.antarcticEntry = it.thirstyCookiePrivateSurface

                    binding.iFirstRelation.tvContent.text = it.thirstyCookiePrivateSurface
                    binding.iFirstPhone.tvContent.text = it.standardInternationalCrossroads
                    binding.iFirstName.tvContent.text = it.sleepyElectricBotanySatellite
                }

                if (!it.afraidQuarterShow.isNullOrEmpty() && !it.actualFareUnableSociety.isNullOrEmpty()) {
                    secondRelationShip = RememberBlankAntRes()
                    secondRelationShip?.furnishedLetterConnection = it.afraidQuarterShow
                    secondRelationShip?.antarcticEntry = it.actualFareUnableSociety

                    binding.iSecondRelation.tvContent.text = it.actualFareUnableSociety
                    binding.iSecondPhone.tvContent.text = it.usedSuccess
                    binding.iSecondName.tvContent.text = it.mistakenPlayroomHardworkingPorterSalesgirl
                }
            }
            checkNextStatus()
        }
        appModel.saveInfo2Suc.observe(asLifecycleOwner) {
            dismissLoading()
            if (it) {
                startActivity(Intent(this@Info2Activity, Info3Activity::class.java))
            }
        }
    }

    private fun initTextChangedListener() {
        binding.etFirstPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etFirstName.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etSecondPhone.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etSecondName.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
    }

    private fun initEvent() {
        binding.llBack.setOnClickListener(this)
        binding.tvNext.setOnClickListener(this)
        binding.iFirstPhone.root.setOnClickListener(this)
        binding.iFirstName.root.setOnClickListener(this)
        binding.iFirstRelation.root.setOnClickListener(this)
        binding.iSecondPhone.root.setOnClickListener(this)
        binding.iSecondName.root.setOnClickListener(this)
        binding.iSecondRelation.root.setOnClickListener(this)
        binding.tvProtocol.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when(v) {
            binding.llBack -> {
                onBackPressed()
            }
            binding.tvNext -> {
                val value1 = if (isGetContactSuc) { binding.iFirstPhone.tvContent.text.toString().trim()} else binding.etFirstPhone.text.toString().trim()
                if (value1.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                val value2 = if (isGetContactSuc) { binding.iFirstName.tvContent.text.toString().trim()} else binding.etFirstName.text.toString().trim()
                if (value2.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                val value3 = relationShip?.furnishedLetterConnection ?: ""
                if (value3.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                val value4 = if (isGetContactSuc) { binding.iSecondPhone.tvContent.text.toString().trim()} else binding.etSecondPhone.text.toString().trim()
                if (value4.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                val value5 = if (isGetContactSuc) { binding.iSecondName.tvContent.text.toString().trim()} else binding.etSecondName.text.toString().trim()
                if (value5.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                val value6 = secondRelationShip?.furnishedLetterConnection ?: ""
                if (value6.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                showLoading()
                appModel.realiseArabPrescription2(
                    mexicanRegardsMistakenRoofInterestingGallery = 3,
                    standardInternationalCrossroads = value1,
                    sleepyElectricBotanySatellite = value2,
                    compressedAnybodyPyramid = value3,
                    usedSuccess = value4,
                    mistakenPlayroomHardworkingPorterSalesgirl =  value5,
                    afraidQuarterShow = value6,
                )
            }
            binding.iFirstName.root -> {
                openContact(100)
            }
            binding.iFirstPhone.root -> {
                openContact(100)
            }
            binding.iFirstRelation.root -> {
                relationShipPicker.setBodyWidth(140)
                relationShipPicker.setIncludeSecrecy(false)
                relationShipPicker.setOnOptionPickedListener { position, item ->
                    relationShip = item as RememberBlankAntRes?
                    binding.iFirstRelation.tvContent.text = relationShipPicker.wheelView.formatItem(position)
                }
                relationShipPicker.wheelLayout
                    .setOnOptionSelectedListener { position, item ->
                        relationShipPicker.titleView.text = relationShipPicker.wheelView.formatItem(position)
                    }
                relationShipPicker.show()
            }
            binding.iSecondName.root -> {
                openContact(200)
            }
            binding.iSecondPhone.root -> {
                openContact(200)
            }
            binding.iSecondRelation.root -> {
                secondRelationShipPicker.setBodyWidth(140)
                secondRelationShipPicker.setIncludeSecrecy(false)
                secondRelationShipPicker.setOnOptionPickedListener { position, item ->
                    secondRelationShip = item as RememberBlankAntRes?
                    binding.iSecondRelation.tvContent.text = secondRelationShipPicker.wheelView.formatItem(position)
                }
                secondRelationShipPicker.wheelLayout
                    .setOnOptionSelectedListener { position, item ->
                        secondRelationShipPicker.titleView.text = secondRelationShipPicker.wheelView.formatItem(position)
                    }
                secondRelationShipPicker.show()
            }
            binding.tvProtocol -> {
                WebViewActivity.jumProtocol(this@Info2Activity)
            }
        }
    }

    private fun openContact(type: Int) {
        val intent = Intent(Intent.ACTION_PICK)
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, type)
        } else {
            changeUI(type)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (resultCode == RESULT_CANCELED) {
//            return
//        }
        if (data == null) {
            changeUI(requestCode)
            return
        }
        if (resultCode == RESULT_OK) {
            val contactUri:Uri?  = data.getData();
            val projection = arrayOf(
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
            )
            val cursor = contentResolver.query(contactUri!!, projection, null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                var number = cursor.getString(numberIndex)
                if (!TextUtils.isEmpty(number)){
                    number = number.replace(" ","",true)
                }
                val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val display_name = cursor.getString(nameIndex)
                setData(number, display_name, requestCode)
            } else {
                changeUI(requestCode)
            }
        }
    }

    private fun setData(number: String, name: String, type: Int) {
        when(type) {
            100 -> {
                binding.iFirstName.tvContent.text = name
                binding.iFirstPhone.tvContent.text = number
            }
            200 -> {
                binding.iSecondName.tvContent.text = name
                binding.iSecondPhone.tvContent.text = number
            }
        }
    }

    private fun changeUI(requestCode: Int) {
        isGetContactSuc = false
        if (requestCode == 100) {
            binding.iFirstName.root.visible(false)
            binding.iFirstPhone.root.visible(false)
            binding.etFirstName.visible(true)
            binding.etFirstPhone.visible(true)
        }
        if (requestCode == 200) {
            binding.iSecondName.root.visible(false)
            binding.iSecondPhone.root.visible(false)
            binding.etSecondName.visible(true)
            binding.etSecondPhone.visible(true)
        }
    }

    private fun checkNextStatus() {
        if (getNextStatus()) {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_sure_26)
        } else {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_disable_sure_26)
        }
    }
    private fun getNextStatus(): Boolean {
        if (binding.iFirstRelation.tvContent.text.trim().isEmpty() || binding.iSecondRelation.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etFirstName.text.toString().trim().isEmpty() && binding.iFirstName.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etFirstPhone.text.toString().trim().isEmpty() && binding.iFirstPhone.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etSecondName.text.toString().trim().isEmpty() && binding.iSecondName.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etSecondPhone.text.toString().trim().isEmpty() && binding.iSecondPhone.tvContent.text.trim().isEmpty()) {
            return false
        }
        return true
    }

}